var commonCounter = 0;
var totalPrice = 0;
var itemCode = {}, itemName = {}, batchDate = {}, unitPrice = {}, txtFieldVal = {}, objCounter = {}, newStockQnt = {}, tempStockQnt = {}, splitQuantity = {}, cartFieldVal = {};
function addToCart(i){
	itemCode['itemcode' + i] = $('#itemCode'+i).text();
	itemName['itemname' + i] = $('#itemName'+i).text();
	batchDate['batchdate' + i] = $("#batchDate"+i).text();
	unitPrice['unitprice' + i] = parseFloat($("#unitPrice"+i).text());
	txtFieldVal['txtfieldval'+i] = parseFloat($("#quantity"+i).val());
	$("#quantity"+i).val('');
	
	if(!objCounter['objcounter'+i]){
		splitQuantity['splitquantity' + i] = ($("#stockQnt"+i).text()).split(" ");
		newStockQnt['newstockqnt' + i] = parseFloat(splitQuantity['splitquantity' + i][0]);
		tempStockQnt['tempstockqnt' + i] = newStockQnt['newstockqnt' + i];
		if(tempStockQnt['tempstockqnt' + i] >= txtFieldVal['txtfieldval'+i])
			newStockQnt['newstockqnt' + i] = newStockQnt['newstockqnt' + i] - txtFieldVal['txtfieldval'+i];
		objCounter['objcounter' + i] = 1;
		$("#stockQnt"+i).text(newStockQnt['newstockqnt' + i] + " " +splitQuantity['splitquantity' + i][1]);
	}
	else{
		tempStockQnt['tempstockqnt' + i] = newStockQnt['newstockqnt' + i];
		if(tempStockQnt['tempstockqnt' + i] >= txtFieldVal['txtfieldval'+i])
			newStockQnt['newstockqnt' + i] = newStockQnt['newstockqnt' + i] - txtFieldVal['txtfieldval'+i];
		$("#stockQnt"+i).text(newStockQnt['newstockqnt' + i] + " " + splitQuantity['splitquantity' + i][1]);
	}
	
	if(txtFieldVal['txtfieldval'+i] == 0){
		$("#messages").html("<div id='msg1' title='Indika Stores'>You should enter a quantity</div>");
		$( "#msg1" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
	}else if(!txtFieldVal['txtfieldval'+i]){
		$("#messages").html("<div id='msg2' title='Indika Stores'>You should enter a quantity</div>");
		$( "#msg2" ).dialog({ buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
	}else{
		if(tempStockQnt['tempstockqnt' + i] < txtFieldVal['txtfieldval'+i]){
			$("#messages").html("<div id='msg3' title='Indika Stores'>Available quantity is not sufficient for your request</div>");
			$( "#msg3" ).dialog({ buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
		}
		else{
			if(commonCounter == 0){
				var newRow = $(	"<tr><th>Item Name</th><th>Quantity</th><th>Amount</th><th>Delete</th></tr>");
				$('table.cart').append(newRow);
			}
			if(objCounter['objcounter' + i] > 1){
				cartFieldVal['cartfieldval'+i] = parseFloat($("#displayCart input[type=text].cartQty"+i).val()) + txtFieldVal['txtfieldval'+i];
				$("#displayCart input[type=text].cartQty"+i).val(cartFieldVal['cartfieldval'+i]);
				$("#displayCart #amount"+i).text(cartFieldVal['cartfieldval'+i] * unitPrice['unitprice' + i]+" Rs");
			}else{
				$("#displayCart #title").text("Cart Content");
				cartFieldVal['cartfieldval'+i] = txtFieldVal['txtfieldval'+i];
				var newRow = $( "<tr id='row"+i+"'><td><input type='hidden' value='"+itemCode['itemcode' + i]+"' name='itemcode"+i+"'/>"+itemName['itemname' + i]+" </td>"+
									"<td><input type='hidden' value='"+unitPrice['unitprice' + i]+"' name='unitprice"+i+"'/><input type='text' size='6' value='"+cartFieldVal['cartfieldval'+i]+"' class='cartQty"+i+"' name='quantity"+i+"' onkeydown='validateTxt(); testForEnter();' onChange='updateQty("+i+")'/></td>"+
									"<td><input type='hidden' value='"+batchDate['batchdate' + i]+"' name='batchdate"+i+"'/><div id='amount"+i+"'></div></td>"+
									"<td><button type='button' id='deleteBtn' onClick='deleteRow("+i+")'></button></td>"+
								"</tr>");
				$('table.cart').append(newRow);
				$("#displayCart #amount"+i).text(cartFieldVal['cartfieldval'+i] * unitPrice['unitprice' + i]+" Rs");
				objCounter['objcounter' + i]++;
				commonCounter++;
			}
			if(commonCounter > 0){
				$("#finish").html("<button id='submitBtn' type='submit'><img src='public/images/button-img/finish.png'/><span> Finish order </span></button>");
				totalPrice = totalPrice + (unitPrice['unitprice' + i] * txtFieldVal['txtfieldval'+i]);
				$("#total").text("Total Price : "+totalPrice+" Rs/=");
				$("#displayCart #hidden").html("<td><input type='hidden' value='"+totalPrice+"' name='totalprice' /></td>");
				$("#payment").html( "<td>Cash: <input id='custPayment' type='text' onkeydown='validateTxt(); testForEnter();'/></td>"+
									"<td><button type='button' id='opener'  onclick='getBalance()'><img src='public/images/button-img/balance.png'/><span> Get Balance </span></button></td>");
			}
		}
	}
	dTable.fnFilter('');
}

function validateTxt() {
	// Allow: backspace, delete, tab, escape, enter and .
	if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || event.keyCode == 190 || event.keyCode == 110 || 
		 // Allow: Ctrl+A
		(event.keyCode == 65 && event.ctrlKey === true) || 
		 // Allow: home, end, left, right
		(event.keyCode >= 35 && event.keyCode <= 39)) {
			 // let it happen, don't do anything
			 return;
	}
	else {
		if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
			event.preventDefault(); 
		}   
	}
}

function testForEnter() {
	if (event.keyCode == 13) {        
		event.cancelBubble = true;
		event.returnValue = false;
	}
}
function updateQty(i){
	var temp = {}, startedStockQty = {};
	temp['temp'+i] = newStockQnt['newstockqnt' + i];
	startedStockQty['startedstockqty'+i] = parseFloat(splitQuantity['splitquantity' + i][0]);
	cartFieldVal['cartfieldval'+i] = parseFloat($("#displayCart input[type=text].cartQty"+i).val());
	if(cartFieldVal['cartfieldval'+i] > startedStockQty['startedstockqty'+i]){
		$("#messages").html("<div id='msg4' title='Indika Stores'>Available quantity is not enough.");
		$( "#msg4" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
		cartFieldVal['cartfieldval'+i] = startedStockQty['startedstockqty'+i] - temp['temp'+i];
		$("#displayCart input[type=text].cartQty"+i).val(cartFieldVal['cartfieldval'+i]);
	}
	else{
		newStockQnt['newstockqnt' + i] = startedStockQty['startedstockqty'+i] - cartFieldVal['cartfieldval'+i];
		$("#stockQnt"+i).text(newStockQnt['newstockqnt' + i] + " " + splitQuantity['splitquantity' + i][1]);
		$("#displayCart #amount"+i).text(cartFieldVal['cartfieldval'+i] * unitPrice['unitprice' + i]+" Rs");
		totalPrice = totalPrice + (unitPrice['unitprice' + i] * (temp['temp'+i] - newStockQnt['newstockqnt' + i]));
		$("#total").text("Total Price : "+totalPrice+" Rs/=");
		$("#displayCart #hidden").html("<td><input type='hidden' value='"+totalPrice+"' name='totalprice' /></td>");
		$("#finish").html("<button id='submitBtn' type='submit'><img src='public/images/button-img/finish.png'/><span> Finish order </span></button>");
	}
		
}
function deleteRow(i) {
	$("#stockQnt"+i).text(splitQuantity['splitquantity' + i][0] + " " + splitQuantity['splitquantity' + i][1]);
	objCounter['objcounter' + i] = 1;
	totalPrice = totalPrice - (unitPrice['unitprice' + i] * cartFieldVal['cartfieldval'+i]);
	newStockQnt['newstockqnt' + i] = parseFloat(splitQuantity['splitquantity' + i][0]);
	$("#total").text("Total Price : "+totalPrice+" Rs/=");
	$("#displayCart #hidden").html("<td><input type='hidden' value='"+totalPrice+"' name='totalprice' /></td>");
	$("#finish").html("<button id='submitBtn' type='submit'><img src='public/images/button-img/finish.png'/><span> Finish order </span></button>");
	$("#row"+i).remove();
}
function getBalance(){
	var balance = parseFloat($("#payment #custPayment").val()) - totalPrice;
	if(balance >= 0)
		$("#balance").text("Balance : "+balance+" Rs/=");
	else{
		$("#payment #custPayment").val('');
		$("#messages").html("<div id='msg5' title='Indika Stores'>Selling price should be greater than total price.</div>");
		$( "#msg5" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
	}
}